﻿using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace SDCloudSolution.SDCloud.ServiceAgent
{
    public class ServiceManager
    {
        protected List<ServiceModel> Services { get; set; }

        private int _timeOut;
        private string _processPath;
        private string _arguments;
        private string _url;

        public ServiceManager(string processPath, string arguments, string url, int[] portNumbers, int timeOut)
        {
            _processPath = processPath;
            _arguments = arguments;
            _timeOut = timeOut;
            _url = url;

            Services = new List<ServiceModel>();

            Parallel.For(0, portNumbers.Length, (i) =>
            {
                AddService(portNumbers[i]);
            });
        }

        ~ServiceManager()
        {
            RemoveAllServices();
        }

        public void AddService(int portNumber)
        {
            if (Services.All(service => service.PortNumber != portNumber))
            {                
                Services.Add(new ServiceModel(_processPath, _arguments, _url, portNumber, _timeOut));
            }
        }
        public void RemoveService(int portNumber)
        {
            Services.RemoveAll(service => service.PortNumber == portNumber);
        }

        public void RemoveAllServices()
        {
            foreach(var service in Services)
            {
                service.EndProcess();
            }
            Services.RemoveAll(s => true);
        }
        private ServiceModel GetServiceModel(int portNumber)
        {
           return Services.FirstOrDefault(service => service.PortNumber == portNumber);
        }

        private ServiceModel GetFreeService()
        {
            bool serviceFound = false;

            while (!serviceFound)
            {
                var openedService = Services
                    .FirstOrDefault(service => service.State == ServiceState.Open);

                if (openedService != null)
                {
                    return openedService;
                }
            }
            return null;
        }

        public Task<string> GetResponse(string getRoutePath)
        {
            var service = GetFreeService();
            return service.GetResponse(getRoutePath);
        }

        public Task<string> PostResponse(string postRoutePath, HttpContent content)
        {
            var service = GetFreeService();
            return service.PostResponse(postRoutePath, content);
        }
    }
}
